import java.awt.Point;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import com.speljohan.rsbot.accessors.NPC;
import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.script.Calculations;
import com.speljohan.rsbot.script.Constants;
import com.speljohan.rsbot.script.Script;
import com.speljohan.rsbot.script.wrappers.RSItemTile;
import com.speljohan.rsbot.script.wrappers.RSNPC;
import com.speljohan.rsbot.script.wrappers.RSTile;

public class CowOwn3r extends Script {

	private final int KILLCOWS = 0;
	private final int KILLSCRIPT = 1;
	private int action = 0;

	private final int[] COWID = { 1767, 81, 1768, 1766, 397, 2310, 1767 };
	private final int[] STEELARROW = { 886 };

	private final RSTile CowTile = new RSTile(2924, 3275);

	public boolean wants2Eat;

	public int food;

	public void checkEat() {
		final int cHealth = skills
				.getCurrentSkillLevel(Constants.STAT_HITPOINTS);
		final int randomInt = random(7, 9);
		if (cHealth <= randomInt) {
			atInventoryItem(food, "Eat");

		}

	}

	private boolean clickNPC(final RSNPC npc, final String action) {
		if (npc == null) {
			return false;
		}
		final RSTile tile = npc.getLocation();
		if (!tile.isValid()) {
			return false;
		}

		try {
			Point screenLoc = npc.getScreenLocation();
			if (distanceTo(tile) > 6 || !pointOnScreen(screenLoc)) {
				turnToTile(tile);
			}
			if (distanceTo(tile) > 20) {
				walkTileMM(tile);
				return false;
			}
			for (int i = 0; i < 12; i++) {
				screenLoc = npc.getScreenLocation();
				if (!npc.isValid() || !pointOnScreen(screenLoc)) {
					return false;
				}
				moveMouse(screenLoc, 5, 5);
				if (getMenuItems().get(0).toLowerCase().contains(
						npc.getName().toLowerCase())) {
					break;
				}
				if (getMouseLocation().equals(screenLoc)) {
					break;
				}
			}
			final List<String> menuItems = getMenuItems();
			if (menuItems.isEmpty()) {
				return false;
			}
			for (int a = 0; a < menuItems.size(); a++) {
				if (menuItems.get(a).toLowerCase().contains(
						npc.getName().toLowerCase())) {
					if (menuItems.get(0).toLowerCase().contains(
							action.toLowerCase())) {
						clickMouse(true);
						return true;
					} else {
						clickMouse(false);
						return atMenu(action);
					}
				}
			}
		} catch (final Exception e) {
			log.log(Level.SEVERE, "clickNPC(RSNPC, String) error: ", e);
			return false;
		}
		return false;
	}

	private int getAction() {
		if (distanceTo(CowTile) < 50) {
			return KILLCOWS;
		} else {
			return KILLSCRIPT;
		}
	}

	@Override
	public String getAuthor() {
		return "xX Nicole Xx";
	}

	@Override
	public String getName() {
		return "Cow Own3r";
	}

	public RSItemTile getNearestGroundItemByID(final int range, final int[] ids) {
		final int pX = getMyPlayer().getLocation().getX();
		final int pY = getMyPlayer().getLocation().getY();
		final int minX = pX - range;
		final int minY = pY - range;
		final int maxX = pX + range;
		final int maxY = pY + range;
		int dist = 100;
		RSItemTile nItem = null;
		for (int x = minX; x <= maxX; x++) {
			for (int y = minY; y <= maxY; y++) {
				if (Calculations.canReach(new RSTile(x, y), false)) {
					final RSItemTile[] items = getGroundItemsAt(x, y);
					for (final RSItemTile item : items) {
						final int iId = item.getItem().getID();
						for (final int id : ids) {
							if (iId == id) {
								// log(""+id+" at "+x+","+y);
								if (distanceTo(new RSTile(x, y)) < dist) {
									dist = distanceTo(new RSTile(x, y));
									nItem = item;
								}

							}
						}
					}
				}
			}
		}
		return nItem;
	}

	private RSNPC getNearestNextNPCByID(final int... ids) {
		int Dist = 20;
		RSNPC closest = null;
		final int[] validNPCs = Bot.getClient().getNPCIndexArray();
		final NPC[] npcs = Bot.getClient().getNPCArray();

		for (final int element : validNPCs) {
			if (npcs[element] == null) {
				continue;
			}
			final RSNPC Monster = new RSNPC(npcs[element]);
			try {
				for (final int id : ids) {
					if (id != Monster.getID() || Monster.isInCombat()
							|| Monster.getInteracting() != null) {
						continue;
					}
					final int distance = getRealDistanceTo(Monster
							.getLocation(), false);
					if (distance < Dist) {
						Dist = distance;
						closest = Monster;
					}
				}
			} catch (final Exception e) {
			}
		}
		return closest;
	}

	@Override
	public String getScriptCategory() {
		return "Combat";
	}

	@Override
	public String getScriptDescription() {
		String html = "";

		html += "<html>\n";
		html += "<body>\n";
		html += "<h2>" + getName() + " version" + getVersion() + "</h2><br>\n";
		html += "Author: " + getAuthor() + "<br><br>\n";
		html += "Start At Cows next to crafting Guild";
		html += "<br>Based off Ruski's Chicken killer for Fast switching";
		html += "<br>We do Not make any guarantees of Bans.";
		html += "<br>When using this Please use All Antiban. Or similar.";
		html += "<br>This will kill cows next to Crafting guild ONLY";
		html += "<br>It Will NOT get Cow hides, Just amazingly Fast EXP!";
		html += "<br>Enter the ID of food Or just leave blank if you Don't Want to eat<br>";
		html += "ID of food: <input type=\"text\" name=\"eatsies\"><br>";
		html += "</body>\n";
		html += "</html\n";

		return html;
	}

	@Override
	public double getVersion() {
		return 1.0;
	}

	@Override
	public int loop() {
		if (wants2Eat) {
			if (inventoryContains(food)) {
				checkEat();
			}
		}

		action = getAction();
		switch (action) {
		case KILLCOWS:
			runControl();
			final RSItemTile arrow = getNearestGroundItemByID(5, STEELARROW);
			final int randomNum = random(0, 5);
			if (randomNum > 4 && arrow != null) {
				atTile(arrow, "Steel arrow");
				return random(900, 1400);
			}
			if (getMyPlayer().getInteracting() != null) {
				return random(300, 450);
			}

			final RSNPC cow = getNearestNextNPCByID(COWID);
			if (cow != null) {
				if (cow.getInteracting() != null
						&& getMyPlayer().getInteracting() == null) {
					return random(100, 200);
				}

				if (getMyPlayer().getInteracting() == null) {
					clickNPC(cow, "attack");
					return random(800, 1400);
				}
				return random(200, 400);
			}
			return random(500, 1000);

		case KILLSCRIPT:
			log("Stopping scripts - Wrong Tile Position, Please move to Crafting Guild");
			stopAllScripts();
			return random(100, 200);
		}

		return random(400, 800);
	}

	@Override
	public boolean onStart(final Map<String, String> args) {
		log("Started CowOwn3r");
		try {
			if (args.get("eatsies").equals("")) {
				log("You don't want to eat");
				wants2Eat = false;

			}

			else {
				food = Integer.parseInt(args.get("eatsies"));
				log("You want to eat");
				wants2Eat = true;
			}

		} catch (final Exception e) {

		}
		return true;
	}

	private void runControl() {
		if (!isRunning() && getEnergy() > random(20, 30)) {
			setRun(true);
		}
	}

}